package cn.fl.ass.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.cmm.base.framework.utils.DecimalUtils;
import cn.fl.project.service.IPrjPrdPaySchDService;
import cn.fl.project.vo.PrjPrdPaySchMVO;
import org.apache.axis2.databinding.types.xsd.Decimal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.ass.service.IAssTrailCarDInfService;
import cn.fl.ass.service.IAssTrailCarDService;
import cn.fl.ass.service.IAssTrailCarFlowInsMcrLngService;
import cn.fl.ass.vo.AssTrailCarDInfVO;
import cn.fl.ass.vo.AssTrailCarDVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.insurance.vo.InsApplicationVO;
import cn.fl.mcr.vo.McrBillMVO;
import cn.fl.system.constant.SysLogConstant;
import fl.ass.facade.condition.AssTrailCarDQueryCondition;

/**
 * @Description: 拖车实际信息明细表 控制层
 */
@Controller
@RequestMapping("/ass/assTrailCarFlowInfo")
public class AssTrailCarFlowInfoController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(AssTrailCarFlowInfoController.class);

	/**
	 * AssTrailCarDInf 服务层BEAN
	 */
	@Autowired
	private IAssTrailCarDInfService assTrailCarDInfService;
	@Autowired
	private IPrjPrdPaySchDService prjPrdPaySchDService;
	/**
	 * AssTrailCarD 服务层BEAN
	 */
	@Autowired
	private IAssTrailCarDService assTrailCarDService;
	
	@Autowired
	private IAssTrailCarFlowInsMcrLngService assTrailCarFlowInsMcrLngService;

	
	/**
	 * 获取经营贷信息
	 */
	@RequestMapping(value = "/getInsPayInfo.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getInsPayInfo(HttpServletRequest request, HttpServletResponse response) {
		//获取页面参数
		String tcMasterId = request.getParameter("tcMasterId");
		if(StringUtils.isEmpty(tcMasterId)){
			return null;
		}else{
			AssTrailCarDQueryCondition qc = new AssTrailCarDQueryCondition();
			qc.setMasterId(Long.valueOf(tcMasterId));
			qc.setIsDel(BaseConstant.IS_YESNO_NO);
			qc.setIsHis(BaseConstant.IS_YESNO_NO);
			List<AssTrailCarDVO> voList = this.assTrailCarDService.searchDetailList(qc);
			Long cstId=0L;
			if(CollectionUtils.isNotEmpty(voList)){
				cstId=voList.get(0).getCstId();
			}else{
				return null;
			}
			List<InsApplicationVO> insappvo=assTrailCarFlowInsMcrLngService.getInsPayInfo(cstId);
			if(insappvo==null){
				return null;
			}
			ListPageVO<InsApplicationVO> listPage = new ListPageVO<InsApplicationVO>(insappvo, insappvo.size());
			return listPage;
		}

		//return null;
	}
	/**
	 * 获取经营贷信息
	 */
	@RequestMapping(value = "/getMcrBillInfo.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getMcrBillInfo(HttpServletRequest request, HttpServletResponse response) {
		//获取页面参数
		String tcMasterId = request.getParameter("tcMasterId");
		String loanBziType=request.getParameter("loanType");
		if(StringUtils.isEmpty(tcMasterId)){
			return null;
		}else{
			AssTrailCarDQueryCondition qc = new AssTrailCarDQueryCondition();
			qc.setMasterId(Long.valueOf(tcMasterId));
			qc.setIsDel(BaseConstant.IS_YESNO_NO);
			qc.setIsHis(BaseConstant.IS_YESNO_NO);
			List<AssTrailCarDVO> voList = this.assTrailCarDService.searchDetailList(qc);
			Long cstId=0L;
			if(CollectionUtils.isNotEmpty(voList)){
				cstId=voList.get(0).getCstId();
			}else{
				return null;
			}
			List<McrBillMVO> mcrbills=assTrailCarFlowInsMcrLngService.getMcrBillInfo(cstId, loanBziType);
			
			ListPageVO<McrBillMVO> listPage = new ListPageVO<McrBillMVO>(mcrbills, mcrbills.size());
			return listPage;
		}
	
		
	}
	
	/**
	 * 修改赎回主表信息
	 */
	@RequestMapping(value = "/saveInsLngMCrInfo.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object saveInsLngMCrInfo(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		//获取页面业务参数
		String busid = request.getParameter("busid");
		//获取页面业务参数
		String processInstanceId = request.getParameter("processId");
		//获取页面业务参数
		String taskDefKey = request.getParameter("taskDefKey");
		//经营贷的数据
		String ligergrid_loan = request.getParameter("ligergrid_loan");
		ArrayList<McrBillMVO> mcrbillloans= JSON.parseObject(ligergrid_loan,new TypeReference<ArrayList<McrBillMVO>>() {});
		//保险贷信息
		String ligergrid_ins = request.getParameter("ligergrid_ins");
		ArrayList<InsApplicationVO> mcrbillinss= JSON.parseObject(ligergrid_ins,new TypeReference<ArrayList<InsApplicationVO>>() {});
		//lng贷信息
		String ligergrid_lng = request.getParameter("ligergrid_lng");
		ArrayList<McrBillMVO> mcrbilllngs= JSON.parseObject(ligergrid_lng,new TypeReference<ArrayList<McrBillMVO>>() {});
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		try {
			if(StringUtils.isEmpty(processInstanceId)||StringUtils.isEmpty(busid)||StringUtils.isEmpty(taskDefKey)){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				return result;
			}
			if((mcrbillloans!=null&&mcrbillloans.size()>0)
					||(mcrbillinss!=null&&mcrbillinss.size()>0)
					||(mcrbilllngs!=null&&mcrbilllngs.size()>0)){
				//保存数据
				assTrailCarFlowInsMcrLngService.saveOrupdateflowInfo(mcrbillloans, mcrbillinss, mcrbilllngs, busid, processInstanceId, taskDefKey);
				result.setSuccess(BaseConstant.IS_YESNO_NO);
			}else{
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
			}

		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.newLogger("保存赎回主表信息异常").setThrowable(ex).setKeys("redeemId:" + busid).info();
		}
		return result;
	}
	
	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getAllMoney.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getAllMoney(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("tcMasterId");
		//获取页面参数
		String tcMasterId = request.getParameter("tcMasterId");
		List<Long> ids = new ArrayList<Long>();
		if(StringUtils.isEmpty(tcMasterId)){
			return null;
		}else{
			AssTrailCarDQueryCondition qc = new AssTrailCarDQueryCondition();
			qc.setMasterId(Long.valueOf(tcMasterId));
			qc.setIsDel(BaseConstant.IS_YESNO_NO);
			qc.setIsHis(BaseConstant.IS_YESNO_NO);
			List<AssTrailCarDVO> voList = this.assTrailCarDService.searchDetailList(qc);
			//获取拖车详细信息IdList
			if(CollectionUtils.isNotEmpty(voList)){
				for (AssTrailCarDVO vo : voList) {
					ids.add(vo.getId());
				}
			}
		}
	
		List<AssTrailCarDVO> assTcvos = this.assTrailCarDService.selectByDetailId(ids);
		AssTrailCarDVO assTcvo=new AssTrailCarDVO();
		if(null!=assTcvos&&assTcvos.size()>0){
			assTcvo=assTcvos.get(0);
		}
		
		Long tcInfoId=assTcvo.getInfoId();
		Long paySchId=assTcvo.getPaySchId();
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		
		try {
			AssTrailCarDInfVO vo = this.assTrailCarDInfService.selectById(tcInfoId);
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				return result;
			}
			if(null==vo.getFutureAmt()){
				
				List<Long> paySchids = new ArrayList<Long>();
				if(StringUtils.isEmpty(paySchId)){
					return result;
				}else{
					paySchids.add(Long.valueOf(paySchId));
				}
				List<AssTrailCarDInfVO> cardinfovos = this.assTrailCarDInfService.selectMoneyByPaySchId(paySchids);
				AssTrailCarDInfVO cardinfovo=new AssTrailCarDInfVO();
				if(null!=cardinfovos&&cardinfovos.size()>0){
					cardinfovo=cardinfovos.get(0);
				}
				// TODO

				PrjPrdPaySchMVO pay = new PrjPrdPaySchMVO();
				this.prjPrdPaySchDService.computeLoanArAmt(pay,String.valueOf(paySchId));
				Long leftArAmt = DecimalUtils.convertYuanToFen(pay.getFinalPayAmt()); //剩余待核销金额
                Long overRentAmt=cardinfovo.getOverRentAmt()==null?0L:cardinfovo.getOverRentAmt(); // 逾期租金
                Long futureAmt =cardinfovo.getFutureAmt()==null?0L:cardinfovo.getFutureAmt();// 未来本金
//                Long actPayAmt=vo.getActPayAmt()==null?0L:vo.getActPayAmt(); //实际支付金额
                Long otherAmt=vo.getOtherAmt()==null?0L:vo.getOtherAmt(); //其他费用
                Long performanceAmt =cardinfovo.getPerformanceAmt()==null?0L:cardinfovo.getPerformanceAmt();//履约保证金
                Long insureAmt =cardinfovo.getInsureAmt()==null?0L:cardinfovo.getInsureAmt();//保险保证金
                Long riskAmt =cardinfovo.getRiskAmt()==null?0L:cardinfovo.getRiskAmt();//风险保证金
                //Long rsrvPc=assTcvo.getRsrvPc()==null?0L:assTcvo.getRsrvPc();
                Long baseAmt=(overRentAmt+futureAmt+leftArAmt+otherAmt)-performanceAmt-insureAmt-riskAmt;
                vo.setBaseAmt(baseAmt);//设置保底价格
			}
			Long cstId=assTcvo.getCstId();
			//保险数据
			List<InsApplicationVO> insappvo=assTrailCarFlowInsMcrLngService.getInsPayInfo(cstId);
			List<McrBillMVO> mcrbills=assTrailCarFlowInsMcrLngService.getMcrBillInfo(cstId, null);
			Long baseAllAmt=vo.getBaseAmt();
			if(insappvo!=null){
				for(InsApplicationVO insvo:insappvo){
					baseAllAmt+=insvo.getClearAmt();
				}
			}
			if(mcrbills!=null){
				for(McrBillMVO loanvo:mcrbills){
					baseAllAmt+=loanvo.getClearAmt();
				}
			}
			vo.setBaseAmt(baseAllAmt);
			result.setSuccess(BaseConstant.IS_YESNO_YES);
			result.setData(vo);
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.newLogger("获取保底价小贷价格保险数据异常 BaseException").setThrowable(ex).setKeys("id:" + id).info();
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.newLogger("获取保底价小贷价格保险数据异常 Exception").setThrowable(ex).setKeys("id:" + id).info();
		}
		return result;
		
	}
	
	
	
}

